#include "client.h"
#include "ui_client.h"

Client::Client(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Client)
{
    ui->setupUi(this);
    //限制年龄输入只能是数字。
    QRegExp AgeRegExpression("^\d+$");
    QRegExpValidator AgeRegExpressionValidator(AgeRegExpression);
    ui->ui_TextEditAge->setValidator(&AgeRegExpressionValidator);

    SoftwareStatus *ui_StatusBar = new SoftwareStatus(this);
    m_LabelMessage = new QLabel(this);

    ui->ui_BtnSubmit->setEnabled(false);

    ui->statusbar->addPermanentWidget(ui_StatusBar);
    ui->statusbar->addWidget(m_LabelMessage);

    //m_Socket = new QTcpSocket();

    connect(this, SIGNAL(signal_status_changed(int)), ui_StatusBar, SLOT(on_status_changed(int)));
    connect(ui->ui_TextEditPwd, SIGNAL(textChanged(QString)), this, SLOT(slot_check()));
    connect(ui->ui_TextEditName, SIGNAL(textChanged(QString)), this, SLOT(slot_check()));
    connect(ui->ui_TextEditClass, SIGNAL(textChanged(QString)), this, SLOT(slot_check()));
    connect(ui->ui_TextEditStudentNumber, SIGNAL(textChanged(QString)), this, SLOT(slot_check()));
    connect(ui->ui_TextEditAge, SIGNAL(textChanged(QString)), this, SLOT(slot_check()));

    //connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slot_error()));
    //connect(m_Socket, SIGNAL(connected()), this, SLOT(slot_connected()));
    //connect(m_Socket, SIGNAL(disconnected()), this, SLOT(slot_disconnected()));

//    f_UpdateUI();

    slot_check();
}

Client::~Client()
{
    if(m_Socket != nullptr)
    {
        if(m_Socket->isOpen())
        {
            m_Socket->disconnectFromHost();
            m_Socket->close();
        }
    }
    delete ui;
}

void Client::f_UpdateUI()
{
    QSettings *config;
    try {
       config = new QSettings("./Config/Config.ini", QSettings::IniFormat);
    } catch (std::bad_alloc) {
        emit signal_status_changed(SoftwareStatus::Error);
        QMessageBox::critical(this, "错误", "申请内存空间失败!", QMessageBox::Yes);

        delete config;
        qApp->exit(-1);
    }
    if(config->contains("DATA/IP"))
    {
        m_IP = config->value("DATA/IP").toString();
        ui->ui_LabelIPAddress->setText(m_IP);
    }
    if(config->contains("DATA/PORT"))
    {
        m_Port = config->value("DATA/PORT").toString();
        ui->ui_LabelPort->setText(m_Port);
    }
    delete config;
}

QString Client::f_Md5(QString pwd)
{
    QString MD5;
    QByteArray str;
    str = QCryptographicHash::hash(pwd.toLatin1(),QCryptographicHash::Md5);
    MD5.append(str.toHex());

    return MD5;
}

void Client::f_SetIPAddress(QString IP)
{
    m_IP = IP;
}

void Client::f_SetPort(QString Port)
{
    m_Port = Port;
}

void Client::f_StartTCPConnection()
{

        m_Socket = new QTcpSocket();
        connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slot_error()));
        connect(m_Socket, SIGNAL(connected()), this, SLOT(slot_connected()));
        connect(m_Socket, SIGNAL(disconnected()), this, SLOT(slot_disconnected()));
        m_Socket->connectToHost(QHostAddress(m_IP), m_Port.toUInt());
}


void Client::on_action_C_triggered()
{
    this->close();
}

void Client::on_ui_BtnSubmit_clicked()
{
    connect(m_Socket, SIGNAL(readyRead()), this, SLOT(slot_AcceptData()));
    if(ui->ui_TextEditAge->text().toInt() >= 100)
    {
        emit signal_status_changed(SoftwareStatus::Warning);
        if(QMessageBox::Yes == QMessageBox::warning(this,
                                                    "警告",
                                                    "年龄不能大于100岁！",
                                                    QMessageBox::Yes))
        {
            emit signal_status_changed(SoftwareStatus::Normal);
            ui->ui_TextEditAge->clear();

            return;
        }
    }
    m_Socket->write(QString("$$"
                            + f_Md5(ui->ui_TextEditPwd->text())
                            + "#" + ui->ui_TextEditClass->text()
                            + "#" + ui->ui_TextEditStudentNumber->text()
                            + "#" + ui->ui_TextEditAge->text()
                            + "#" + ui->ui_TextEditName->text()
                            + "$$").toUtf8());
}

void Client::slot_check()
{
    if(ui->ui_TextEditName->text().isEmpty()
            || ui->ui_TextEditClass->text().isEmpty()
            || ui->ui_TextEditAge->text().isEmpty()
            || ui->ui_TextEditPwd->text().isEmpty()
            || ui->ui_TextEditStudentNumber->text().isEmpty()
            || ui->ui_TextEditPwd->text().length() <6)
    {
        ui->ui_BtnSubmit->setEnabled(false);
        m_LabelMessage->setText(QString("<font color=\"red\">一个或多个项目未完善</font>"));

        emit signal_status_changed(SoftwareStatus::Warning);
    }
    else
    {
        m_LabelMessage->clear();
        ui->ui_BtnSubmit->setEnabled(true);

        emit signal_status_changed(SoftwareStatus::Normal);
    }
}

void Client::on_action_IP_I_triggered()
{
    IPSet *widget_IPSet = new IPSet();
    if(!widget_IPSet->exec())
    {
        delete widget_IPSet;
        return;
    }
    else
    {
        QString IP = widget_IPSet->f_GetIPAddress();
        QString Port = widget_IPSet->f_GetPort();

        QSettings *config;
        try {
           config = new QSettings("./Config/Config.ini", QSettings::IniFormat);
        } catch (std::bad_alloc) {
            emit signal_status_changed(SoftwareStatus::Error);
            QMessageBox::critical(this, "错误", "申请内存空间失败!", QMessageBox::Yes);

            delete config;
            qApp->exit(-1);
        }

        m_IP = IP;
        m_Port = Port;
        config->setValue("DATA/IP", IP);
        config->setValue("DATA/PORT", Port);

        ui->ui_BtnSubmit->setEnabled(false);
        ui->ui_TextEditAge->setEnabled(false);
        ui->ui_TextEditPwd->setEnabled(false);
        ui->ui_TextEditName->setEnabled(false);
        ui->ui_TextEditClass->setEnabled(false);
        ui->ui_TextEditStudentNumber->setEnabled(false);

        emit signal_status_changed(SoftwareStatus::Info);
        m_LabelMessage->setText("等待连接");

        delete config;
        f_UpdateUI();
        f_StartTCPConnection();
    }

    delete widget_IPSet;
}

void Client::slot_error()
{
    //失能控件
    ui->ui_BtnSubmit->setEnabled(false);
    ui->ui_TextEditAge->setEnabled(false);
    ui->ui_TextEditPwd->setEnabled(false);
    ui->ui_TextEditName->setEnabled(false);
    ui->ui_TextEditClass->setEnabled(false);
    ui->ui_TextEditStudentNumber->setEnabled(false);

    emit signal_status_changed(SoftwareStatus::Error);
    m_LabelMessage->setText(m_Socket->errorString());
}

void Client::slot_AcceptData()
{
    QString Message = m_Socket->readAll();
    if(Message == "ACK")
    {
        QMessageBox::information(this, "提示", "注册成功!");
    }
    else
    {
        emit signal_status_changed(SoftwareStatus::Error);
        QMessageBox::information(this, "提示", "注册失败，可能是因为信息未完整传输到服务器");
    }
    emit signal_status_changed(SoftwareStatus::Normal);
}

void Client::slot_connected()
{
    ui->ui_BtnSubmit->setEnabled(true);
    ui->ui_TextEditAge->setEnabled(true);
    ui->ui_TextEditPwd->setEnabled(true);
    ui->ui_TextEditName->setEnabled(true);
    ui->ui_TextEditClass->setEnabled(true);
    ui->ui_TextEditStudentNumber->setEnabled(true);

    emit signal_status_changed(SoftwareStatus::Normal);
    m_LabelMessage->clear();

    slot_check();
}

void Client::slot_disconnected()
{
    if(m_Socket->isOpen())
    {
        m_Socket->abort();
    }
    slot_error();

    m_Socket->deleteLater();
}
